package real.yingke;
import java.util.*;

import linked.ListNode;

public class TwoSum {

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * .
     * @param l1 ListNode类 参数1
     * @param l2 ListNode类 参数2
     * @return ListNode类
     */
    public ListNode addTwoNumbers (ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) return l1 == null ? l2 : l1;
        List<Integer> s1 = new ArrayList<>(), s2 = new ArrayList<>();
        while (l1 != null) {
            s1.add(l1.val);
            l1 = l1.next;
        }
        while (l2 != null) {
            s2.add(l2.val);
            l2 = l2.next;
        }

        if (s1.size() < s2.size()) {
            List<Integer> temp = s2;
            s2 = s1;
            s1 = temp;
        }
        int len1 = s1.size(), len2 = s2.size();
        List<Integer> res = new ArrayList<>();
        int sum, carry = 0;
        for (int i = 0; i < len2; i++) {
            sum = (s1.get(len1 - i - 1) + s2.get(len2 - i - 1)) + carry;
            carry = sum / 10;
            sum %= 10;
            res.add(sum);
        }

        for (int i = len2; i < len1; i++) {
            sum = s1.get(len1 - i - 1) + carry;
            carry = sum / 10;
            sum %= 10;
            res.add(sum);
        }
        if (carry == 1) {
            res.add(1);
        }

        ListNode dummy = new ListNode(0), result = dummy;
        int size = res.size();
        for (int i = 0; i < size; i++) {
            dummy.next = new ListNode(res.get(size - 1 - i));
            dummy = dummy.next;
        }
        return result.next;
    }
}
    
}
